<template>
    <div>
      <!-- 卡片视图 -->
        <el-card shadow="always">
            <!-- 面包屑导航 -->
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>公司内部</el-breadcrumb-item>
                <el-breadcrumb-item>用户组</el-breadcrumb-item>
            </el-breadcrumb>
            <!-- 搜索框 -->
            <el-input style="width:280px;" placeholder="请输入组名" class="search" v-model="searchData" clearable>
                <i slot="prefix" class="el-input__icon el-icon-search"></i>>
                <el-button slot="append" @click="searchBtn" :disabled="isDisabled">搜索</el-button>
            </el-input>
            <!-- 添加用户组按钮 -->
            <el-button type="primary" style="margin-left:65%;" @click="openAddGroupDialog">添加用户组</el-button>
            <!-- 数据列表 -->
            <el-table :data="tableData" border style="width: 100%">
                <el-table-column type="index" label="#" width="75"></el-table-column>
                <el-table-column prop="title" label="组名"></el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="启用" placement="top" :enterable='false' v-if="scope.row.status == 1">
                          <el-button size="mini" type="success" @click="enableBtn(scope.row)">
                            <i class="iconfont icon-qiyong" style="margin:0 auto"></i>
                          </el-button>
                        </el-tooltip>

                        <el-tooltip class="item" effect="dark" content="禁用" placement="top" :enterable='false'>
                            <el-button size="mini" type="danger" @click="disableBtn(scope.row)" v-if="scope.row.status == 2">
                                <i class="iconfont icon-jinyong" style="margin:0 auto"></i>
                            </el-button>
                        </el-tooltip>

                        <el-tooltip class="item" effect="dark" content="设置权限" placement="top" :enterable='false'>
                            <el-button size="mini" type="warning" :disabled="scope.row.status==2?false:true" @click="setRights(scope.row)">
                                <i class="el-icon-setting" style="margin:0 auto"></i>
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="p"
              :page-sizes="[15, 20, 50, 80]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="count"
            ></el-pagination>
        </el-card>

        <!-- 分配权限弹窗-->
        <el-dialog title="设置权限" :visible.sync="dialogVisible" width="70%" @close="setRightDialogClose">
            <el-tree
              :data="treeData"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              :default-expanded-keys="defaultKeys"
              :default-checked-keys="defaultKeys"
              ref="treeRef"
            ></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="commitRightsBtn">确定</el-button>
            </span>
        </el-dialog>

        <!-- 添加用户组弹窗 -->

        <el-dialog title="提示" :visible.sync="dialogVisibleAddGroup" width="30%" @submit.native.prevent>
            <el-form :model="addGroupForm" style="margin-left:15%">
                <el-form-item label="组名:">
                    <input type="text"  v-model="addGroupForm.title" class="input_">
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleAddGroup = false">取 消</el-button>
                <el-button type="primary" @click="addGroup" ref="addGroupRef">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {get} from "../../../../public/API/query";
import config from '../../../../public/config'

export default {
    data() {
        return {
            //列表数据
            tableData: [],
            //查询参数
            p: 1,
            limit: 10,
            //总条数
            count: null,
            dialogVisible: false,
            currentPage4: 1,
            searchData: "",
            value: [],
            // 树形控件的属性绑定对象
            defaultProps: {
                children: "_child",
                label: "title",
            },
            treeData: [],
            dialogVisibleAddGroup: false,
            addGroupForm: {
                title: "",
            },
            //默认选择节点ID数组
            defaultKeys: [],
            isDisabled: false,
            userId: "",
        };
    },
    methods: {
        //设置权限
        setRights(value) {
            this.userId = value.id;
            this.dialogVisible = true;
            // const {
            //   data: res,
            // } = await this.$axios.get(
            //   `https://v3-l.xinhehonggu.comcompany/group/powerPage`,
            //   { params: { id: value.id, token: this.queryInfo.token } }
            // );
            // this.treeData = res.data;

            // ;(function getTree(data){
            //   for (const i in data) {
            //     if (!data._child && data.isCheck == 1) {
            //       this.defaultKeys.push(data[i].id)
            //     }else{
            //       getTree(data[i]._child)
            //     }
            //   }
            // })(this.treeData)

            // this.defaultKeys = res.data.info.menuIds.split(",").map((i) => i * 1);
            get(`company/group/powerPage`, { id: value.id },(res) => {
                this.treeData = res.data;
                var that = this;
                (function getTree(data) {
                    for (const i in data) {
                        if (!data[i]._child && data[i].isCheck == 1) {
                            that.defaultKeys.push(data[i].id);
                        } else {
                            getTree(data[i]._child);
                        }
                    }
                })(this.treeData);
            });
        },
        // 重置节点ID数组
        setRightDialogClose() {
            this.defaultKeys = [];
        },
        //提交权限按钮
        commitRightsBtn() {
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys(),
            ];
            var newArr = [];
            (function delMax(arr, data) {
                for (const i in data) {
                    var hasId = arr.findIndex((item) => {
                        return item == data[i].id;
                    });
                    if (hasId != -1 && !data[i]._child) {
                        newArr.push(arr[hasId]);
                    } else {
                        delMax(arr, data[i]._child);
                    }
                }
            })(keys, this.treeData);
            const idStr = newArr.join(",");
            // const { data: res } = await this.$axios.get(
            //   `https://v3-l.xinhehonggu.com/company/group/submitPower`,
            //   {
            //     params: {
            //       token: this.queryInfo.token,
            //       id: this.userId,
            //       menuIds: idStr,
            //     },
            //   }
            // );
            if (idStr) {
               get(`company/group/submitPower`,{
                  id: this.userId,
                  menuIds: idStr,
                },(res) => {
                    if(res.code == 200){
                        this.$message.success("设置权限成功");
                        this.dialogVisible = false;
                    }else{
                        this.$message.error(res.data)
                    }
                }); 
            }else{
                this.$message.error('请选择权限')
            }
            
        },
        //获取用户组列表数据
        getTableData() {
             console.log(123);
            if (this.searchData) {
                get(`company/group/index`,{
                    limit:this.limit,
                    p:this.p,
                    title:this.searchData
                },res=>{
                    
                    this.tableData = res.data._list;
                    this.count = res.data.count;
                    }
                );
            }else{
        
                get(`company/group/index`,{
                    limit:this.limit,
                    p:this.p
                },res=>{
                     console.log(res);
                    this.tableData = res.data._list;
                    this.count = res.data.count;
                    
                    }
                );
            }
        },
        handleSizeChange(newSize) {
            this.limit = newSize;
            this.getTableData();
        },
        handleCurrentChange(newPage) {
            this.p = newPage;
            this.getTableData();
        },
        //添加用户组
        openAddGroupDialog() {
            this.dialogVisibleAddGroup = true;
        },
        //添加用户组
        addGroup() {
            get('company/group/addSub',{
                    title: this.addGroupForm.title,
                },res=>{
                    if (res.code === 200) {
                        this.$message.success("添加用户组成功");
                        this.addGroupForm.title = "";
                        this.dialogVisibleAddGroup = false;
                        this.getTableData();
                    } else if (res.code === 301) {
                        this.$message.error("用户名已存在,请更改");
                        this.$refs.addGroupRef.disabled = true;
                    } else {
                        this.$message.error("添加用户组失败");
                    }
                }
            );
        },
        //启用按钮
        enableBtn(value) {
            get(`company/group/enable`,{
                    id: value.id,
                },res=>{
                    if (res.code == 200) {
                        this.$message.success("启用成功");
                        this.getTableData();
                    } else if (res.code == 301) {
                        this.$message.error("已启用");
                    } else {
                       this.$message.error("启用失败");
                    }
                }
            );
        },
        //禁用按钮
        disableBtn(value) {
          get(`company/group/disable`,{
                  id: value.id,
              },res=>{
                  if (res.code == 200) {
                      this.$message.success("禁用成功");
                      this.getTableData();
                  } else if (res.code == 301) {
                      this.$message.error("已禁用");
                  } else {
                      this.$message.error("禁用失败");
                  }
              }
          );
        },
        //搜索功能
        searchBtn() {
            this.isDisabled = true;
            get(`company/group/index`,{
                   title: this.searchData,
                },res=>{
                    console.log(res)
                    this.count = res.data.count;
                    this.tableData = res.data._list;
                }
            );
        },
        // //递归获取选中三级ID
        // getLeafId(obj,arr) {
        //   if(!obj._child && obj.isCheck == -1){
        //     return arr.push(obj.id)
        //   }
        //   for (let item of obj._child) {
        //     this.getLeafId(item,arr)
        //   }

        // },
    },
    watch: {
        searchData: function() {
            if (!this.searchData) {
                this.getTableData();
            }
            if (this.searchData) {
                this.isDisabled = false;
            }
        },
    },

    created() {
        this.getTableData();
        if (!this.searchData) {
            this.isDisabled = true;
        }
    },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
    margin-bottom: 30px;
}
.el-input {
    margin-bottom: 30px;
    width: 280px;
    margin-right: 30px;
}
.el-pagination {
    margin-top: 30px;
}
.addRulesWrap {
    margin-left: 80px;
}
.addRules {
    position: absolute;
    right: 25%;
    bottom: 5%;
}
.disable {
    margin-left: 15px;
}
</style>
